package com.xidian.GMS.controller;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import com.xidian.GMS.entity.State;
import com.xidian.GMS.entity.Users;
import com.xidian.GMS.service.LoginService;
import com.xidian.GMS.util.VerificationCode;

@Controller
public class LoginController {
	
	@Autowired
	private LoginService log;



	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public State login(String account,String password,String code,HttpSession session){
		boolean flagcode = log.checkCode(session, code);
		State state = new State();
		if(flagcode == false){
            state.setSuccess("2");
            System.out.println(state);
            return state;
		}
		else {
			Users user = log.login(account, password);
			if(user == null){
				 state.setSuccess("0");
				 System.out.println(state);
				 return state;
			}
			else{
				session.setAttribute("user", user);
				state.setSuccess("1");
				return state;
			}
		}
	}
	
	@RequestMapping(value="/autologin",method=RequestMethod.POST)
	@ResponseBody
	public State autologin(Users user,HttpSession session){
		    State state = new State();
		    Users users = log.login(user.getAccount(), user.getPassword());
			if(users == null){
				 state.setSuccess("0");
				 System.out.println(state);
				 return state;
			}
			else{
				session.setAttribute("user", users);
				state.setSuccess("1");
				return state;
			}
	}
	
	
	@RequestMapping(value="/user/check.jpg",method=RequestMethod.GET)
	public void createCode(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {  
        // 通知浏览器不要缓存  
        response.setHeader("Expires", "-1");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setHeader("Pragma", "-1");  
        VerificationCode util = VerificationCode.Instance();  
        // 将验证码输入到session中，用来验证  
        String code = util.getString();  
        session.setAttribute("code", code);  
        // 输出打web页面  
        ImageIO.write(util.getImage(), "jpg", response.getOutputStream());  
        
        
       // return "forward:/WEB-INF/views/login.html";
    }  

}
